#include "widget.h"
#include "ui_widget.h"
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <sstream>

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
  ui->setupUi(this);
  setWindowTitle("自己封装HTTP");

}

Widget::~Widget() {
  delete ui;
}


void Widget::showMessage(const QString &info) {
  ui->messageShoxEdit->appendPlainText(info);

}

void Widget::on_btnSend_clicked() {
  QString urlString = ui->messageEdit->text();

  //解析URL 例如:https://www.example.com:8080/path/to/file?param1=value1&param2=value2#fragment"
  QUrl url(urlString);
  QString host = url.host();               // 输出 "www.example.com"
  int port = url.port();               // 输出 8080
  QString path =  url.path();               // 输出 "/path/to/file"

  if(port <=0){
      port = 80;
  }

  std::ostringstream response;

  m_client.setUrl(host.toStdString(),port);
  if (m_client.get(path.toStdString())) {
      response << "响应头部:" << std::endl;
      for (const auto& line : m_client.getHeaders()) {
          response << line << std::endl;
      }

     response << "响应消息体:" << std::endl;
     response<< m_client.getBody() << std::endl;
  } else {
      response << "请求失败" << std::endl;
  }

  std::string st = response.str();
  showMessage(st.c_str());
}

